<template>
  <div class="ipfs-storage">
    <h2>IPFS Hash Storage</h2>

    <div class="input-section">
      <input v-model="hashInput" type="text" placeholder="输入IPFS Hash" class="hash-input" />
      <button :disabled="isLoading || !hashInput" class="store-btn" @click="storeHash">
        {{ isLoading ? '存储中...' : '存储Hash' }}
      </button>
    </div>

    <div v-if="storedHashes.length" class="hash-list">
      <h3>已存储的Hashes:</h3>
      <ul>
        <li v-for="(hash, index) in storedHashes" :key="index">
          <span class="hash-text">{{ hash }}</span>
          <a :href="`https://ipfs.io/ipfs/${hash}`" target="_blank" class="view-link"> 查看 </a>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useInjectedWeb3 } from '../composables/useWeb3';
import { showToast as showMessage } from 'vant';

const { provider, signer, isConnected, init, read, write } = useInjectedWeb3();

const hashInput = ref('');
const storedHashes = ref([]); // 确保初始化为一个空数组
const isLoading = ref(false);

onMounted(async () => {
  try {
    await init();
    await loadStoredHashes();
  } catch (error) {
    console.error('初始化失败:', error);
    showMessage('初始化失败');
  }
});

async function loadStoredHashes() {
  try {
    const hashes = await read('getAllHashes');
    storedHashes.value = hashes || []; // 确保赋值为数组
  } catch (error) {
    console.error('加载Hashes失败:', error);
    showMessage('加载Hashes失败');
  }
}

async function storeHash() {
  if (!hashInput.value) return;

  try {
    isLoading.value = true;
    await write('storeHash', hashInput.value);
    showMessage('Hash存储成功');
    await loadStoredHashes();
    hashInput.value = '';
    isLoading.value = false;
  } catch (error) {
    console.error('存储Hash失败:', error);
    showMessage('存储Hash失败');
    isLoading.value = false;
  }
}
</script>

<style scoped>
.ipfs-storage {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.input-section {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.hash-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.store-btn {
  padding: 8px 16px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.store-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.hash-list {
  background-color: #f5f5f5;
  padding: 20px;
  border-radius: 4px;
}

.hash-list ul {
  list-style: none;
  padding: 0;
}

.hash-list li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

.hash-text {
  font-family: monospace;
  word-break: break-all;
}

.view-link {
  color: #2196f3;
  text-decoration: none;
  margin-left: 10px;
}

.view-link:hover {
  text-decoration: underline;
}
</style>
